A Step-by-Step Guide to Building an Application with Flex
Macromedia
This article provides a comprehensive introduction to Flex. You will first explore Flex Store, a shopping cart application built with Flex. Then you will be introduced you to some of the best practices behind the Flex Store architecture. And finally, you will have the opportunity to experience with the Flex programming language by rewriting a subset of the Flex Store application.
Just as they do with traditional applications, Flex architects and developers:
- Define and implement a suitable object model for the application
- Choose appropriate relationships between objects (inheritance vs. association, etc...)
- Identify and implement applicable design patterns
- Define and implement a suitable messaging scheme between local objects
- Define and implement the appropriate infrastructure to communicate with remote services
- Implement a framework for the application
This guide walks you through a guided selling application that includes product display, sorting and filtering, drag-and-drop selection, a shopping cart, and a complete checkout procedure. While the application is small, it illustrates some of the most common patterns for building much larger Flex applications.
Requirements
You can follow along with this tutorial by browsing the online example of the Flex Store, or you can install Macromedia Flex.
If you browse the online example of the Flex Store, download the sample files for this tutorial:
flexstore.zip (4K)
Macromedia Flex
(Installed and running on any server and platform supported by Flex. Note that the Flex trial is available on CD from the Macromedia store for $8.99. To learn more about the Flex trial, please read the Flex Frequently Asked Questions.)
Flex Store
To see the Flex Store, browse to [flex default server]/samples/flexstore/flexstore.mxml on your server or browse the online version.
-
Browse the products by selecting items from the grid.
The first thing you notice is that the application is structured as a basic master/detail which, although simple, can’t be done in HTML. As you choose products from the grid on the left, the product detail displays on the right. A basic HTML application would require the browser to reload the page to show detail. Flex applications cache the data on the client, minimizing roundtrips to the server and making the application highly responsive.
-
Move the slider under the product list to filter products based on price.
As you move the slider, the products that don’t meet the price criteria fade, so that you see only those that do. This example of guided selling shows how developers can offer users visual clues that allow users to maintain context for their actions and not get lost in multiple pages.
-
Choose Price from the Sort by pop-up menu.
Macromedia Flash Player’s ability to maintain state on the client allows developers to implement features like client sorting so that users can view the same data in different formats. For similar functionality, a server-based application would have to go back to the server each time and often to the data source. In a Flex application, the data is cached on the client for easy manipulation and immediate response to user requests.
-
Add items to the shopping cart by using the numeric stepper to choose quantity and selecting the Add to Cart button.
Again, where HTML would require another page to display the items in the shopping cart, Flex displays them without page refresh, automatically calculating and displaying the total using client-side logic. This example of direct manipulation gives the user immediate feedback while maintaining the context of the overall application.
-
Select the graphic of the item in the Product Details pane and drag it into the Shopping Cart.
Flex contains a number of managers that allow you to easily implement advanced application functionality like drag and drop.
-
Choose different columns in the Shopping Cart data grid to sort by that column.
The data grid is one of the rich components in the standard Flex component library, many of which include built-in capabilities like sorting.
-
Choose the Checkout button. The left pane displays the Accordion navigation container to help a customer step through the check out procedure.
One of the things that is broken on the web is form processing. The checkout process is typically comprised of a number of forms; if you make a mistake early in the process, you don't find out until you submit the form, often multiple pages later. If you click the back button, you're unsure whether your entered data will still be there. Likewise, customers often abandon the process before they finish, making the rate of completed transactions far less than is acceptable. Flex provides components that let you to structure the data input process for greater usability—one example of that is the Accordion container. With the Accordion container, you can organize multiple forms in a single pane and include built-in effects to expand and contract the appropriate forms.
-
Begin the check out process by entering your name. Click the back button in your browser, as if to buy another product (you can add additional products if you wish). Click the forward button to return to the checkout.
With Flex's built-in history manager, users navigate with back and forward buttons, as they would in a page-based application. The Accordion container automatically preserves the state so the data you entered is still there.
-
Enter an invalid email address and press tab to go onto the next field.
A red border appears around the invalid form field, indicating that you entered invalid data; moving your mouse over the field displays an appropriate error message. With Flex’s powerful data binding features, developers can easily add validation to form fields, offering users immediate feedback.
-
Choose the Shipping Information pane and select the different radio button options.
The Order Summary updates, indicating the price based on your shipping choice, and gives you immediate feedback not only about the price of shipping but the total based on your shipping choice.
Code Walkthrough
You build Flex applications with MXML, a tag-based, declarative language for laying out the user interface and ActionScript script for procedural logic. Read An Overview of MXML, the Macromedia Flex Markup Language, for more information. The code required to build the Flex Store application is organized similarly to how you would architect a typical enterprise application, partitioning the application using a model, view, controller design pattern.
The following is the class diagram describing the application:

Figure 1. A UML describes the application.
Creating a Flex application is just like creating a Java, .NET or any other object-oriented application—you create and assemble classes. The Flex class diagram shows three types of classes with user interface (view) classes implemented in MXML and the models in Action Script. The controller classes are the web services and bindings that are part of the data management capabilities in Flex.
To see the files associated with the Flex Store application, browse to default Flex server install\samples on your installation or in the files you downloaded in the Requirements section at the beginning of this article. Open the flexstore.mxml file in your favorite text editor or IDE.
Encapsulation and Reuse
The flexstore.mxml file is the main class of the application and aggregates the different views available in the application: ThumbnailView, GridView, and CartView. Because they are user interface classes, they are also defined in MXML. You implement the views as classes and when you create a class in Flex, you are able to reference it as a tag. In this case, the user can see the same data displayed as a series of thumbnail graphics or in a data grid. The view classes reference the same data model but do not include the data. This lets you to partition the application for more maintainable code.
With Flex, developers can encapsulate functionality and reference it as tags; this is a real boon to reuse and team development. Developers assembling the application don’t have to know how the component was created; they simply reference it as a tag.
Event Model
To provide loose coupling and reusability, Flex enables component communication through an event model that will be familiar to Java and .NET programmers. The event model allows components to register as listeners to events so that they are notified when that event is triggered. An example this is in flexstore.mxml where it registers itemSelected and checkOut for CartView.mxml. Because of this registration, you don’t have to hard code the display of the checkout view, instead you dispatch a checkout event and the listener components react appropriately.
Data Management
You access dynamic data in three different ways: through web services, as a call to a remote Java object, or as XML over HTTP. The Flex Store application shows an example of a web service invocation where the Flex web service tag does all of the plumbing. It takes care of the serialization and deserialization of data as well as the service brokering. You define your web service declaratively by pointing at the WSDL file and Flex does the rest.
Flex’s data binding allows you to bind the property of one component to the property of another component. You typically use it in a data retrieval scenario where the property of a user interface component is bound to a property of a model component (maintaining good separation of model and view) while letting you write a minimal amount of code to display data in user interface components. The flexstore.mxml application file defines a model named catalog where the catalog model is bound to the result of the web service invocation. The thumbnail view and grid view are then both bound to the catalog model with the curly brace binding syntax, a very readable and elegant means of binding.
MXML Components
Browse CartView.mxml on your server and view the code in your text editor (CartView is part of the flexstore.zip, available in the Requirements section).
The CartView class is an example of a reusable MXML component.


Figures 2 and 3. A reusable MXML component and its code.
For each MXML component you create, Flex generates an ActionScript class where the specified root defines which class it inherits. In CartView, the root node is VBox, so the CartView class extends VBox.
ActionScript Components
Open ShoppingCart.as on your server and view the code in your text editor (ShoppingCart.as is part of the flexstore.zip, available in the Requirements section).
Shopping cart is a model class created in ActionScript. ActionScript 2.0 is a strongly typed, object oriented language and with a few syntactical differences, looks very much like a Java or C# class. Since ShoppingCart has no user interface, you use ActionScript so you have the programmatic control you need to create the model. The ShoppingCart model defines the functions you need to track what items are in the cart, how many there are and the total price for the items.
Cascading Style Sheets
The main.css file sets the font and colors for the application. Flex allows you to use standard cascading style sheets so that you can change styles in your application without touching the code.
Managers
Flex contains a series of managers as part of its application model. With the managers, you can easily implement commonly used functionality in MXML and ActionScript. For example, Flex contains a history manager that allows you to control application behavior in relation to browser back and forward button events. It also includes a Drag and Drop Manager that allows you to easily add that capability to your application (see CartView_script.as). With the ToolTip Manager, you can create tooltips for any visual component by setting a single attribute.
Writing Code
Although Flex makes it very easy to structure an enterprise application using best practices design, it is also a very easy to create compelling experiences in very few lines of code. In this section, you'll recreate some of the functionality you saw in the Flex Store application. Specifically, you will call a web service, create model to hold your data, populate the model with a web service, invoke a method to get data, create the event to trigger the method, and bind the incoming data to a user interface control. Note that this section only applies to you if you have installed Flex on your server.
-
Type the following code in your favorite text editor or IDE:
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" height="600">
The first thing you do is set up your application by setting the XML version and the application tag. The xmlns property in the tag specifies the XML namespace. Flex examples use the mx namespace for readability but it is optional. You can use the default namespace by not specifying a prefix and you can specify additional namespaces for references to custom tags.
-
Call a web service to get your data. Copy the following code:
<mx:WebService id="srv" wsdl="@ContextRoot()/services/CatalogWS?wsdl"> <mx:operation name="getList"/> </mx:WebService>
-
Create the model to hold your data and populate it with the web service. Copy the following code:
<mx:Model id="catalog"> {srv.getList.result} </mx:Model> -
You must add a button to trigger the event that gets the data. Copy the following code:
<mx:Button label="Get Data" click="srv.getList()"/>
-
To display your data and close the application, use the grid view by copying the following into your code:
<mx:DataGrid dataProvider="{catalog}"></mx:DataGrid> </Application>
-
Save your code to flex default install\samples\flexstore\demo.mxml and browse to http://flex default install/samples/flexstore/demo.mxml
With those few lines of code, you can access and display data from a web service. By default, the data grid displays all of the data returned from the web service but this isn't what your user wants to view.
-
To format the data grid to show only the product name and price, add the following code between the
dataProvider="{catalog}"statement and the</DataGrid>tag:<mx:columns> <mx:Array> <mx:DataGridColumn columnName="name" headerText="Name" width="200"/> <mx:DataGridColumn columnName="price" headerText="Price" width="100"/> </mx:Array> </mx:columns>
-
Save your file and view it in the browser.
You can also display the same data in a different view, in this case as a grid of thumbnail images.
-
To do this, enter the following after the data grid block and before the close application tag:
<mx:Tile label="Thumbnails"> <mx:Repeater id="list" dataProvider="{catalog}"> <mx:VBox> <mx:Image source="{list.currentItem.image}" width="75" height="70"/> <mx:Label text="{list.currentItem.name}"/> </mx:VBox> </mx:Repeater> </mx:Tile>The Repeater object lets you dynamically repeat any number of controls or containers specified in MXML tags, at runtime. Flex repeats the control or container based on an array of dynamic data, such as an Array object returned from a web service.
You use the tile container to display the items that you iterate over in this example. The tile container is a layout manager that lays out its children in one or more vertical columns or horizontal rows, starting new rows or columns as necessary.
-
Save your file and view it in the browser.
While it is nice to see your data in two different views, it isn't a particularly well organized. With Flex, you can easily organize the data on the screen by supplying a number of navigators. For this example, you'll organize the two views into a tab navigator.
-
Surround the data grid block with the Canvas tag:
<mx:Canvas label=”Grid”>
Data grid block
</mx:Canvas>A navigator contains other containers, so you first wrap the data grid in a container tag. The label is what will display in the tab of the tab navigator.
-
Add a label to the tile container by entering your label inside of the
<mx:Tile>tag so that it reads:<mx:Tile label=”Thumbnails”>
-
Surround the
<mx:Canvas>and</mx:Tile>tags with the opening and closing tab navigator tags:<mx:TabNavigator> <mx: Canvas label=”Grid”> . . . </mx:Tile> </mx:TabNavigator>
-
Save your file and view it in the browser. The views now display in two tabs.
The final file should look like this:
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" height="600"> <mx:WebService id="srv" wsdl="@ContextRoot()/services/CatalogWS?wsdl"> <mx:operation name="getList"/> </mx:WebService> <mx:Model id="catalog">{srv.getList.result }</mx:Model> <mx:Button label="Get Data" click="srv.getList()"/> <mx:TabNavigator> <mx:Canvas label="Grid"> <mx:DataGrid dataProvider="{catalog}"> <mx:columns> <mx:Array> <mx:DataGridColumn columnName="name" headerText="Name" width="200"/> <mx:DataGridColumn columnName="price" headerText="Price" width="100"/> </mx:Array> </mx:columns> </mx:DataGrid> </mx:Canvas> <mx:Tile label="Thumbnails"> <mx:Repeater id="list" dataProvider="{catalog}"> <mx:VBox> <mx:Image source="{list.currentItem.image}" width="75" height="70"/> <mx:Label text="{list.currentItem.name}"/> </mx:VBox> </mx:Repeater> </mx:Tile> </mx:TabNavigator> </mx:Application>
That's an amazing amount of functionality in only 26 lines of code and that's just the beginning. With over 45 components and controls available, developers can quickly and effectively create great user interfaces that offer users a new level of responsiveness and usability and in turn, offer businesses a more effective way to do business on the web.
While the Flex Store example is a simple one, it points out three important principles:
- Experience matters
- Good user experience doesn't mean sacrificing good architecture
- Good user experiences come from good design
Flex Store shows that even in a simple design, the client side data model and Flex's rich user interface controls and behaviors allows developers to create responsive, intuitive user interfaces. The architecture of Flex Store represents how Flex Store integrates with best practices enterprise architectures and allows teams of developers to participate. And finally, Flex's default HALO design, as well as the ease with which designer and developers work together, makes it easy for Flex applications to embody the best practices design that makes for great user experiences. Read more about HALO in Understanding the Macromedia Flex Experience Model, by Mike Sundermeyer.
For more examples of Flex code, see the Flex Samples Explorer in http://flex default install/samples/explorer/explorer.mxml if you've installed Flex. You will find a number of small code samples that show how to access data, set security, apply behaviors, and many other tasks. If you haven't installed Flex, check out the Flex Application Examples. Check out the Flex Developer Center Getting Started area get more familiar with Flex.